﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSP.Dao.CommonDao;
using CSP.Dao.IObjectDaos.CSP;
using CSP.DataAccess;
using CSP.Model.CSP;

namespace CSP.Dao.ObjectDaos.CSP
{
    public class ServiceTypeDao : CSPCommonDao, IServiceTypeDao
    {
        public ServiceTypeDao(CSPContext context, bool isTransaction = false)
            : base(context, isTransaction)
        { }

        public ICollection<Model.CSP.ServiceType> FindAll()
        {
            return _context.ServiceTypes.ToArray();
        }

        public Model.CSP.ServiceType GetDataById(int id)
        {
            return _context.ServiceTypes.FirstOrDefault(a => a.Id == id);
        }

        public ICollection<Model.CSP.ServiceType> GeDatatByIds(int[] Ids)
        {
            return _context.ServiceTypes.Where(a => Ids.Contains(a.Id)).ToArray();
        }

        public void Add(Model.CSP.ServiceType obj)
        {
            _context.ServiceTypes.Add(obj);
            _context.SaveChanges();
        }

        public void Update(Model.CSP.ServiceType obj)
        {
            ServiceType serviceType = GetDataById(obj.Id);
            if (serviceType != null)
            {
                serviceType = obj;
            }
            _context.SaveChanges();
        }

        public ServiceType DeleteById(int id)
        {
            ServiceType serviceType = GetDataById(id);
            _context.ServiceTypes.Remove(serviceType);
            _context.SaveChanges();

            return serviceType;
        }

        public List<int> GetServiceIdsByServiceTypeId(int serviceTypeId)
        {
            List<int> result = new List<int>();
            var rels = _context.ServiceTypes.Include(typeof(ServiceInfoServiceTypeRel).Name).Where(s => s.Id == serviceTypeId).Select(s => s.ServiceInfoServiceTypeRels);
            if (rels.Count() != 0)
            {
                foreach (var rel in rels)
                {
                    foreach (var item in rel)
                    {
                        result.Add(item.ServiceInfoId);
                    }
                }
            }

            return result;
        }
    }
}
